import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

// Flutter通过cookie的方式将登录态同步给h5
class FlutterH5LoginSyncByCookie extends StatefulWidget {
  const FlutterH5LoginSyncByCookie({super.key});

  @override
  State<FlutterH5LoginSyncByCookie> createState() =>
      _FlutterH5LoginSyncByCookieState();
}

class _FlutterH5LoginSyncByCookieState
    extends State<FlutterH5LoginSyncByCookie> {
  WebViewCookieManager cookieManager = WebViewCookieManager();
  late WebViewController controller;

  get _loginBtn => FilledButton(
    onPressed: () {
      controller.loadRequest(
        Uri.parse(
          'https://www.geekailab.com/io/flutter-trip/Flutter2JSByUrl.html?name=xxx',
        ),
      );
    },
    child: Text('加载h5', style: TextStyle(color: Colors.white)),
  );

  get _setCookieBtn => FilledButton(
    onPressed: () {
      _onSetCookie(context);
    },
    child: Text('设置cookie', style: TextStyle(color: Colors.white)),
  );

  get _clearCookieBtn => FilledButton(
    onPressed: () {
      _onClearCookie(context);
    },
    child: Text('清除cookie', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter通过cookie的方式将登录态同步给h5'),
        actions: [_loginBtn, _setCookieBtn, _clearCookieBtn],
      ),
      body: WebViewWidget(controller: controller),
    );
  }

  // 设置cookie
  void _onSetCookie(BuildContext context) async {
    await cookieManager.setCookie(
      const WebViewCookie(
        name: 'token',
        value: 'tokenFoo',
        domain: 'www.geekailab.com',
        path: '/',
      ),
    );
    await cookieManager.setCookie(
      const WebViewCookie(
        name: 'uid',
        value: '14858',
        domain: 'www.geekailab.com',
        path: '',
      ),
    );
    // 也可以在flutter中获取cookie
    final Object cookies = await controller.runJavaScriptReturningResult(
      'document.cookie',
    );
    debugPrint(cookies.toString());
  }

  void _onClearCookie(BuildContext context) async {
    await cookieManager.clearCookies();
    debugPrint('çookie清除成功');
  }
}
